import * as vscode from 'vscode';
import { ChatManager, Message } from './chatManager';

export class ChatViewProvider implements vscode.WebviewViewProvider {
    public static readonly viewType = 'aiChatView';

    private _view?: vscode.WebviewView;
    private _extensionUri: vscode.Uri;
    private _chatManager: ChatManager;

    constructor(extensionUri: vscode.Uri, chatManager: ChatManager) {
        this._extensionUri = extensionUri;
        this._chatManager = chatManager;
    }

    public resolveWebviewView(
        webviewView: vscode.WebviewView,
        context: vscode.WebviewViewResolveContext,
        _token: vscode.CancellationToken,
    ) {
        this._view = webviewView;

        webviewView.webview.options = {
            // 允许访问扩展的资源
            localResourceRoots: [
                this._extensionUri
            ],
            enableScripts: true
        };

        // 设置初始HTML内容
        webviewView.webview.html = this._getHtmlForWebview(webviewView.webview);

        // 监听消息更新
        this._chatManager.onMessagesUpdated(() => {
            this._updateMessages();
        });

        // 接收来自Webview的消息
        webviewView.webview.onDidReceiveMessage(async (data) => {
            switch (data.type) {
                case 'sendMessage':
                    if (data.value) {
                        // 添加用户消息
                        this._chatManager.addMessage('user', data.value);
                        
                        // 添加"正在思考"提示
                        this._chatManager.addMessage('agent', '...');
                        
                        // 模拟AI响应延迟
                        setTimeout(() => {
                            // 移除"正在思考"提示
                            this._chatManager.removeLastMessage();
                            
                            // 获取并添加AI响应
                            this._chatManager.getAIResponseFromRZ(data.value).then(response => {
                                this._chatManager.addMessage('agent', response);
                            });
                        }, 1500);
                    }
                    return;
            }
        });

        // 初始更新消息列表
        this._updateMessages();
    }

    // 更新消息列表
    private _updateMessages() {
        if (this._view) {
            const messages = this._chatManager.getMessages();
            this._view.webview.postMessage({
                type: 'updateMessages',
                value: messages
            });
        }
    }

    // 生成Webview的HTML内容
    private _getHtmlForWebview(webview: vscode.Webview) {
        // 获取样式资源的URI
        const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(
            this._extensionUri, 'media', 'reset.css'
        ));
        const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(
            this._extensionUri, 'media', 'vscode.css'
        ));

        // 使用非cecure源允许内联样式
        return `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>AI Chat</title>
                <link href="${styleResetUri}" rel="stylesheet">
                <link href="${styleVSCodeUri}" rel="stylesheet">
                <style>
                    .chat-container {
                        display: flex;
                        flex-direction: column;
                        height: 100vh;
                        max-height: 100vh;
                    }
                    
                    .messages-container {
                        flex: 1;
                        overflow-y: auto;
                        padding: 10px;
                        display: flex;
                        flex-direction: column;
                        gap: 10px;
                    }
                    
                    .message {
                        max-width: 80%;
                        padding: 8px 12px;
                        border-radius: 4px;
                        margin: 4px 0;
                    }
                    
                    .user-message {
                        background-color: var(--vscode-button-background);
                        color: var(--vscode-button-foreground);
                        align-self: flex-end;
                    }
                    
                    .agent-message {
                        background-color: var(--vscode-sideBar-background);
                        color: var(--vscode-sideBar-foreground);
                        align-self: flex-start;
                    }
                    
                    .input-container {
                        display: flex;
                        padding: 10px;
                        border-top: 1px solid var(--vscode-editorGroupHeader-tabsBorder);
                        flex-shrink: 0;
                    }
                    
                    #messageInput {
                        flex: 1;
                        padding: 8px;
                        background-color: var(--vscode-input-background);
                        color: var(--vscode-input-foreground);
                        border: 1px solid var(--vscode-input-border);
                        border-radius: 4px;
                    }
                </style>
            </head>
            <body>
                <div class="chat-container">
                    <div class="messages-container" id="messagesContainer"></div>
                    <div class="input-container">
                        <input 
                            type="text" 
                            id="messageInput" 
                            placeholder="Type your message and press Enter..."
                        >
                    </div>
                </div>

                <script>
                    const vscode = acquireVsCodeApi();
                    const messagesContainer = document.getElementById('messagesContainer');
                    const messageInput = document.getElementById('messageInput');

                    // 接收来自扩展的消息
                    window.addEventListener('message', event => {
                        const data = event.data;
                        
                        switch (data.type) {
                            case 'updateMessages':
                                updateMessages(data.value);
                                break;
                        }
                    });

                    // 更新消息列表
                    function updateMessages(messages) {
                        messagesContainer.innerHTML = '';
                        
                        messages.forEach(message => {
                            const messageDiv = document.createElement('div');
                            messageDiv.className = \`message \${message.sender === 'user' ? 'user-message' : 'agent-message'}\`;
                            messageDiv.textContent = message.content;
                            messagesContainer.appendChild(messageDiv);
                        });
                        
                        // 滚动到底部
                        messagesContainer.scrollTop = messagesContainer.scrollHeight;
                    }

                    // 处理输入框回车事件
                    messageInput.addEventListener('keydown', event => {
                        if (event.key === 'Enter' && messageInput.value.trim() !== '') {
                            vscode.postMessage({
                                type: 'sendMessage',
                                value: messageInput.value.trim()
                            });
                            
                            messageInput.value = '';
                        }
                    });

                    // 自动聚焦输入框
                    messageInput.focus();
                </script>
            </body>
            </html>`;
    }
}
    